package com.fit.pages.user;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.util.EnumSelectModel;


import com.fit.entities.User;
import com.fit.model.userType.UserType;
import com.fit.pages.Confirmation;
import com.fit.dao.user.UserDAO;

public class Edit {

	@Property
	@Persist
	private User user;
	@Inject
	private UserDAO userDAO;
	@InjectPage
	private AddUser addUser;
	@InjectPage
	private Confirmation confirmation;
	
	@Property
	@Persist
	private UserType userType;
	@Inject
	private Messages messages;
	
	
	public SelectModel getUserTypes() {
		return new EnumSelectModel(UserType.class, messages);
	}
	
	
	Object onActivate(Long id) {
		user = userDAO.findByID(id);
		if (user == null) {
			confirmation.setError("Greska prilikom prikaza zapisa korisnika! ");
			return confirmation;
		}
		return null;
	}

	@CommitAfter
	Object onSuccess() {
		try {
			user.setType(userType.toString());
			userDAO.update(user);
			addUser.setMsg("User succesifuly changed!");
			return addUser;
		} catch (Exception e) {
			confirmation.setError("Greska prilikom brisanja zapisa korisnika! ");
			return confirmation;
		}

	}
}
